home *** CD-ROM | disk | FTP | other *** search
/ SGI Freeware 1999 August / SGI Freeware 1999 August.iso / dist / fw_perl.idb / usr / freeware / catman / u_man / cat1 / perltoot.Z / perltoot
Encoding:
Text File  |  1998-10-28  |  89.1 KB  |  2,509 lines

  1.  
  2.  
  3.  
  4.      PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  5.  
  6.  
  7.  
  8.      NNNNAAAAMMMMEEEE
  9.       perltoot - Tom's object-oriented tutorial for    perl
  10.  
  11.      DDDDEEEESSSSCCCCRRRRIIIIPPPPTTTTIIIIOOOONNNN
  12.       Object-oriented programming is a big seller these days.
  13.       Some managers    would rather have objects than sliced bread.
  14.       Why is that?    What's so special about    an object?  Just what
  15.       _i_s an    object anyway?
  16.  
  17.       An object is nothing but a way of tucking away complex
  18.       behaviours into a neat little    easy-to-use bundle.  (This is
  19.       what professors call abstraction.) Smart people who have
  20.       nothing to do    but sit    around for weeks on end    figuring out
  21.       really hard problems make these nifty    objects    that even
  22.       regular people can use. (This    is what    professors call
  23.       software reuse.)  Users (well, programmers) can play with
  24.       this little bundle all they want, but    they aren't to open it
  25.       up and mess with the insides.     Just like an expensive    piece
  26.       of hardware, the contract says that you void the warranty if
  27.       you muck with    the cover.  So don't do    that.
  28.  
  29.       The heart of objects is the class, a protected little
  30.       private namespace full of data and functions.     A class is a
  31.       set of related routines that addresses some problem area.
  32.       You can think    of it as a user-defined    type.  The Perl
  33.       package mechanism, also used for more    traditional modules,
  34.       is used for class modules as well.  Objects "live" in    a
  35.       class, meaning that they belong to some package.
  36.  
  37.       More often than not, the class provides the user with    little
  38.       bundles.  These bundles are objects.    They know whose    class
  39.       they belong to, and how to behave.  Users ask    the class to
  40.       do something,    like "give me an object."  Or they can ask one
  41.       of these objects to do something.  Asking a class to do
  42.       something for    you is calling a _c_l_a_s_s _m_e_t_h_o_d.    Asking an
  43.       object to do something for you is calling an _o_b_j_e_c_t _m_e_t_h_o_d.
  44.       Asking either    a class    (usually) or an    object (sometimes) to
  45.       give you back    an object is calling a _c_o_n_s_t_r_u_c_t_o_r, which is
  46.       just a kind of method.
  47.  
  48.       That's all well and good, but    how is an object different
  49.       from any other Perl data type?  Just what is an object
  50.       _r_e_a_l_l_y; that is, what's its fundamental type?     The answer to
  51.       the first question is    easy.  An object is different from any
  52.       other    data type in Perl in one and only one way:  you    may
  53.       dereference it using not merely string or numeric subscripts
  54.       as with simple arrays    and hashes, but    with named subroutine
  55.       calls.  In a word, with _m_e_t_h_o_d_s.
  56.  
  57.       The answer to    the second question is that it's a reference,
  58.       and not just any reference, mind you,    but one    whose referent
  59.       has been _b_l_e_s_s()ed into a particular class (read: package).
  60.  
  61.  
  62.  
  63.      Page 1                        (printed 10/23/98)
  64.  
  65.  
  66.  
  67.  
  68.  
  69.  
  70.      PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  71.  
  72.  
  73.  
  74.       What kind of reference?  Well, the answer to that one    is a
  75.       bit less concrete.  That's because in    Perl the designer of
  76.       the class can    employ any sort    of reference they'd like as
  77.       the underlying intrinsic data    type.  It could    be a scalar,
  78.       an array, or a hash reference.  It could even    be a code
  79.       reference.  But because of its inherent flexibility, an
  80.       object is usually a hash reference.
  81.  
  82.      CCCCrrrreeeeaaaattttiiiinnnngggg aaaa    CCCCllllaaaassssssss
  83.       Before you create a class, you need to decide    what to    name
  84.       it.  That's because the class    (package) name governs the
  85.       name of the file used    to house it, just as with regular
  86.       modules.  Then, that class (package) should provide one or
  87.       more ways to generate    objects.  Finally, it should provide
  88.       mechanisms to    allow users of its objects to indirectly
  89.       manipulate these objects from    a distance.
  90.  
  91.       For example, let's make a simple Person class    module.     It
  92.       gets stored in the file Person.pm.  If it were called    a
  93.       Happy::Person    class, it would    be stored in the file
  94.       Happy/Person.pm, and its package would become    Happy::Person
  95.       instead of just Person.  (On a personal computer not running
  96.       Unix or Plan 9, but something    like MacOS or VMS, the
  97.       directory separator may be different,    but the    principle is
  98.       the same.)  Do not assume any    formal relationship between
  99.       modules based    on their directory names.  This    is merely a
  100.       grouping convenience,    and has    no effect on inheritance,
  101.       variable accessibility, or anything else.
  102.  
  103.       For this module we aren't going to use Exporter, because
  104.       we're    a well-behaved class module that doesn't export
  105.       anything at all.  In order to    manufacture objects, a class
  106.       needs    to have    a _c_o_n_s_t_r_u_c_t_o_r _m_e_t_h_o_d.  A constructor gives you
  107.       back not just    a regular data type, but a brand-new object in
  108.       that class.  This magic is taken care    of by the _b_l_e_s_s()
  109.       function, whose sole purpose is to enable its    referent to be
  110.       used as an object.  Remember:    being an object    really means
  111.       nothing more than that methods may now be called against it.
  112.  
  113.       While    a constructor may be named anything you'd like,    most
  114.       Perl programmers seem    to like    to call    theirs _n_e_w().
  115.       However, _n_e_w() is not    a reserved word, and a class is    under
  116.       no obligation    to supply such.     Some programmers have also
  117.       been known to    use a function with the    same name as the class
  118.       as the constructor.
  119.  
  120.       OOOObbbbjjjjeeeecccctttt RRRReeeepppprrrreeeesssseeeennnnttttaaaattttiiiioooonnnn
  121.  
  122.       By far the most common mechanism used    in Perl    to represent a
  123.       Pascal record, a C struct, or    a C++ class is an anonymous
  124.       hash.     That's    because    a hash has an arbitrary    number of data
  125.       fields, each conveniently accessed by    an arbitrary name of
  126.  
  127.  
  128.  
  129.      Page 2                        (printed 10/23/98)
  130.  
  131.  
  132.  
  133.  
  134.  
  135.  
  136.      PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  137.  
  138.  
  139.  
  140.       your own devising.
  141.  
  142.       If you were just doing a simple struct-like emulation, you
  143.       would    likely go about    it something like this:
  144.  
  145.           $rec = {
  146.           name    => "Jason",
  147.           age    => 23,
  148.           peers    => [ "Norbert",    "Rhys",    "Phineas"],
  149.           };
  150.  
  151.       If you felt like it, you could add a bit of visual
  152.       distinction by up-casing the hash keys:
  153.  
  154.           $rec = {
  155.           NAME    => "Jason",
  156.           AGE    => 23,
  157.           PEERS    => [ "Norbert",    "Rhys",    "Phineas"],
  158.           };
  159.  
  160.       And so you could get at $rec->{NAME} to find "Jason",    or @{
  161.       $rec->{PEERS}    } to get at "Norbert", "Rhys", and "Phineas".
  162.       (Have    you ever noticed how many 23-year-old programmers seem
  163.       to be    named "Jason" these days? :-)
  164.  
  165.       This same model is often used    for classes, although it is
  166.       not considered the pinnacle of programming propriety for
  167.       folks    from outside the class to come waltzing    into an
  168.       object, brazenly accessing its data members directly.
  169.       Generally speaking, an object    should be considered an    opaque
  170.       cookie that you use _o_b_j_e_c_t _m_e_t_h_o_d_s to    access.     Visually,
  171.       methods look like you're dereffing a reference using a
  172.       function name    instead    of brackets or braces.
  173.  
  174.       CCCCllllaaaassssssss    IIIInnnntttteeeerrrrffffaaaacccceeee
  175.  
  176.       Some languages provide a formal syntactic interface to a
  177.       class's methods, but Perl does not.  It relies on you    to
  178.       read the documentation of each class.     If you    try to call an
  179.       undefined method on an object, Perl won't complain, but the
  180.       program will trigger an exception while it's running.
  181.       Likewise, if you call    a method expecting a prime number as
  182.       its argument with a non-prime    one instead, you can't expect
  183.       the compiler to catch    this.  (Well, you can expect it    all
  184.       you like, but    it's not going to happen.)
  185.  
  186.       Let's    suppose    you have a well-educated user of your Person
  187.       class, someone who has read the docs that explain the
  188.       prescribed interface.     Here's    how they might use the Person
  189.       class:
  190.  
  191.           use Person;
  192.  
  193.  
  194.  
  195.      Page 3                        (printed 10/23/98)
  196.  
  197.  
  198.  
  199.  
  200.  
  201.  
  202.      PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  203.  
  204.  
  205.  
  206.           $him = Person->new();
  207.           $him->name("Jason");
  208.           $him->age(23);
  209.           $him->peers( "Norbert", "Rhys", "Phineas"    );
  210.  
  211.           push @All_Recs, $him;  # save object in array for    later
  212.  
  213.           printf "%s is %d years old.\n", $him->name, $him->age;
  214.           print "His peers are: ", join(", ", $him->peers),    "\n";
  215.  
  216.           printf "Last rec's name is %s\n",    $All_Recs[-1]->name;
  217.  
  218.       As you can see, the user of the class    doesn't    know (or at
  219.       least, has no    business paying    attention to the fact) that
  220.       the object has one particular    implementation or another.
  221.       The interface    to the class and its objects is    exclusively
  222.       via methods, and that's all the user of the class should
  223.       ever play with.
  224.  
  225.       CCCCoooonnnnssssttttrrrruuuuccccttttoooorrrrssss aaaannnndddd IIIInnnnssssttttaaaannnncccceeee MMMMeeeetttthhhhooooddddssss
  226.  
  227.       Still, _s_o_m_e_o_n_e has to    know what's in the object.  And    that
  228.       someone is the class.     It implements methods that the
  229.       programmer uses to access the    object.     Here's    how to
  230.       implement the    Person class using the standard    hash-ref-as-
  231.       an-object idiom.  We'll make a class method called _n_e_w() to
  232.       act as the constructor, and three object methods called
  233.       _n_a_m_e(), _a_g_e(), and _p_e_e_r_s() to    get at per-object data hidden
  234.       away in our anonymous    hash.
  235.  
  236.           package Person;
  237.           use strict;
  238.  
  239.           ##################################################
  240.           ## the object constructor    (simplistic version)  ##
  241.           ##################################################
  242.           sub new {
  243.           my $self  = {};
  244.           $self->{NAME}      = undef;
  245.           $self->{AGE}      = undef;
  246.           $self->{PEERS}  = [];
  247.           bless($self);          # but    see below
  248.           return $self;
  249.           }
  250.  
  251.           ##############################################
  252.           ## methods to access per-object data      ##
  253.           ##                      ##
  254.           ## With args, they set the value.     Without  ##
  255.           ## any, they only    retrieve it/them.      ##
  256.           ##############################################
  257.  
  258.  
  259.  
  260.  
  261.      Page 4                        (printed 10/23/98)
  262.  
  263.  
  264.  
  265.  
  266.  
  267.  
  268.      PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  269.  
  270.  
  271.  
  272.           sub name {
  273.           my $self = shift;
  274.           if (@_) { $self->{NAME} = shift }
  275.           return $self->{NAME};
  276.           }
  277.  
  278.           sub age {
  279.           my $self = shift;
  280.           if (@_) { $self->{AGE} = shift }
  281.           return $self->{AGE};
  282.           }
  283.  
  284.           sub peers    {
  285.           my $self = shift;
  286.           if (@_) { @{ $self->{PEERS} }    = @_ }
  287.           return @{ $self->{PEERS} };
  288.           }
  289.  
  290.           1;  # so the require or use succeeds
  291.  
  292.       We've    created    three methods to access    an object's data,
  293.       _n_a_m_e(), _a_g_e(), and _p_e_e_r_s().  These are all substantially
  294.       similar.  If called with an argument,    they set the
  295.       appropriate field; otherwise they return the value held by
  296.       that field, meaning the value    of that    hash key.
  297.  
  298.       PPPPllllaaaannnnnnnniiiinnnngggg ffffoooorrrr tttthhhheeee FFFFuuuuttttuuuurrrreeee:::: BBBBeeeetttttttteeeerrrr CCCCoooonnnnssssttttrrrruuuuccccttttoooorrrrssss
  299.  
  300.       Even though at this point you    may not    even know what it
  301.       means, someday you're    going to worry about inheritance.
  302.       (You can safely ignore this for now and worry    about it later
  303.       if you'd like.)  To ensure that this all works out smoothly,
  304.       you must use the double-argument form    of _b_l_e_s_s().  The
  305.       second argument is the class into which the referent will be
  306.       blessed.  By not assuming our    own class as the default
  307.       second argument and instead using the    class passed into us,
  308.       we make our constructor inheritable.
  309.  
  310.       While    we're at it, let's make    our constructor    a bit more
  311.       flexible.  Rather than being uniquely    a class    method,    we'll
  312.       set it up so that it can be called as    either a class method
  313.       _o_r an    object method.    That way you can say:
  314.  
  315.           $me  = Person->new();
  316.           $him = $me->new();
  317.  
  318.       To do    this, all we have to do    is check whether what was
  319.       passed in was    a reference or not.  If    so, we were invoked as
  320.       an object method, and    we need    to extract the package (class)
  321.       using    the _r_e_f() function.  If    not, we    just use the string
  322.       passed in as the package name    for blessing our referent.
  323.  
  324.  
  325.  
  326.  
  327.      Page 5                        (printed 10/23/98)
  328.  
  329.  
  330.  
  331.  
  332.  
  333.  
  334.      PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  335.  
  336.  
  337.  
  338.           sub new {
  339.           my $proto = shift;
  340.           my $class = ref($proto) || $proto;
  341.           my $self  = {};
  342.           $self->{NAME}      = undef;
  343.           $self->{AGE}      = undef;
  344.           $self->{PEERS}  = [];
  345.           bless    ($self,    $class);
  346.           return $self;
  347.           }
  348.  
  349.       That's about all there is for    constructors.  These methods
  350.       bring    objects    to life, returning neat    little opaque bundles
  351.       to the user to be used in subsequent method calls.
  352.  
  353.       DDDDeeeessssttttrrrruuuuccccttttoooorrrrssss
  354.  
  355.       Every    story has a beginning and an end.  The beginning of
  356.       the object's story is    its constructor, explicitly called
  357.       when the object comes    into existence.     But the ending    of its
  358.       story    is the _d_e_s_t_r_u_c_t_o_r, a method implicitly called when an
  359.       object leaves    this life.  Any    per-object clean-up code is
  360.       placed in the    destructor, which must (in Perl) be called
  361.       DESTROY.
  362.  
  363.       If constructors can have arbitrary names, then why not
  364.       destructors?    Because    while a    constructor is explicitly
  365.       called, a destructor is not.    Destruction happens
  366.       automatically    via Perl's garbage collection (GC) system,
  367.       which    is a quick but somewhat    lazy reference-based GC
  368.       system.  To know what    to call, Perl insists that the
  369.       destructor be    named DESTROY.    Perl's notion of the right
  370.       time to call a destructor is not well-defined    currently,
  371.       which    is why your destructors    should not rely    on when    they
  372.       are called.
  373.  
  374.       Why is DESTROY in all    caps?  Perl on occasion    uses purely
  375.       uppercase function names as a    convention to indicate that
  376.       the function will be automatically called by Perl in some
  377.       way.    Others that are    called implicitly include BEGIN, END,
  378.       AUTOLOAD, plus all methods used by tied objects, described
  379.       in the _p_e_r_l_t_i_e manpage.
  380.  
  381.       In really good object-oriented programming languages,    the
  382.       user doesn't care when the destructor    is called.  It just
  383.       happens when it's supposed to.  In low-level languages
  384.       without any GC at all, there's no way    to depend on this
  385.       happening at the right time, so the programmer must
  386.       explicitly call the destructor to clean up memory and    state,
  387.       crossing their fingers that it's the right time to do    so.
  388.       Unlike C++, an object    destructor is nearly never needed in
  389.       Perl,    and even when it is, explicit invocation is uncalled
  390.  
  391.  
  392.  
  393.      Page 6                        (printed 10/23/98)
  394.  
  395.  
  396.  
  397.  
  398.  
  399.  
  400.      PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  401.  
  402.  
  403.  
  404.       for.    In the case of our Person class, we don't need a
  405.       destructor because Perl takes    care of    simple matters like
  406.       memory deallocation.
  407.  
  408.       The only situation where Perl's reference-based GC won't
  409.       work is when there's a circularity in    the data structure,
  410.       such as:
  411.  
  412.           $this->{WHATEVER}    = $this;
  413.  
  414.       In that case,    you must delete    the self-reference manually if
  415.       you expect your program not to leak memory.  While
  416.       admittedly error-prone, this is the best we can do right
  417.       now.    Nonetheless, rest assured that when your program is
  418.       finished, its    objects' destructors are all duly called.  So
  419.       you are guaranteed that an object _e_v_e_n_t_u_a_l_l_y gets properly
  420.       destroyed, except in the unique case of a program that never
  421.       exits.  (If you're running Perl embedded in another
  422.       application, this full GC pass happens a bit more
  423.       frequently--whenever a thread    shuts down.)
  424.  
  425.       OOOOtttthhhheeeerrrr    OOOObbbbjjjjeeeecccctttt MMMMeeeetttthhhhooooddddssss
  426.  
  427.       The methods we've talked about so far    have either been
  428.       constructors or else simple "data methods", interfaces to
  429.       data stored in the object.  These are    a bit like an object's
  430.       data members in the C++ world, except    that strangers don't
  431.       access them as data.    Instead, they should only access the
  432.       object's data    indirectly via its methods.  This is an
  433.       important rule: in Perl, access to an    object's data should
  434.       _o_n_l_y be made through methods.
  435.  
  436.       Perl doesn't impose restrictions on who gets to use which
  437.       methods.  The    public-versus-private distinction is by
  438.       convention, not syntax.  (Well, unless you use the Alias
  439.       module described below in the    section    on _D_a_t_a    _M_e_m_b_e_r_s    _a_s
  440.       _V_a_r_i_a_b_l_e_s.)  Occasionally you'll see method names beginning
  441.       or ending with an underscore or two.    This marking is    a
  442.       convention indicating    that the methods are private to    that
  443.       class    alone and sometimes to its closest acquaintances, its
  444.       immediate subclasses.     But this distinction is not enforced
  445.       by Perl itself.  It's    up to the programmer to    behave.
  446.  
  447.       There's no reason to limit methods to    those that simply
  448.       access data.    Methods    can do anything    at all.     The key point
  449.       is that they're invoked against an object or a class.     Let's
  450.       say we'd like    object methods that do more than fetch or set
  451.       one particular field.
  452.  
  453.  
  454.  
  455.  
  456.  
  457.  
  458.  
  459.      Page 7                        (printed 10/23/98)
  460.  
  461.  
  462.  
  463.  
  464.  
  465.  
  466.      PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  467.  
  468.  
  469.  
  470.           sub exclaim {
  471.           my $self = shift;
  472.           return sprintf "Hi, I'm %s, age %d, working with %s",
  473.               $self->{NAME}, $self->{AGE}, join(", ", $self->{PEERS});
  474.           }
  475.  
  476.       Or maybe even    one like this:
  477.  
  478.           sub happy_birthday {
  479.           my $self = shift;
  480.           return ++$self->{AGE};
  481.           }
  482.  
  483.       Some might argue that    one should go at these this way:
  484.  
  485.           sub exclaim {
  486.           my $self = shift;
  487.           return sprintf "Hi, I'm %s, age %d, working with %s",
  488.               $self->name, $self->age, join(", ", $self->peers);
  489.           }
  490.  
  491.           sub happy_birthday {
  492.           my $self = shift;
  493.           return $self->age( $self->age() + 1 );
  494.           }
  495.  
  496.       But since these methods are all executing in the class
  497.       itself, this may not be critical.  There are tradeoffs to be
  498.       made.     Using direct hash access is faster (about an order of
  499.       magnitude faster, in fact), and it's more convenient when
  500.       you want to interpolate in strings.  But using methods (the
  501.       external interface) internally shields not just the users of
  502.       your class but even you yourself from    changes    in your    data
  503.       representation.
  504.  
  505.      CCCCllllaaaassssssss DDDDaaaattttaaaa
  506.       What about "class data", data    items common to    each object in
  507.       a class?  What would you want    that for?  Well, in your
  508.       Person class,    you might like to keep track of    the total
  509.       people alive.     How do    you implement that?
  510.  
  511.       You _c_o_u_l_d make it a global variable called $Person::Census.
  512.       But about only reason    you'd do that would be if you _w_a_n_t_e_d
  513.       people to be able to get at your class data directly.     They
  514.       could    just say $Person::Census and play around with it.
  515.       Maybe    this is    ok in your design scheme.  You might even
  516.       conceivably want to make it an exported variable.  To    be
  517.       exportable, a    variable must be a (package) global.  If this
  518.       were a traditional module rather than    an object-oriented
  519.       one, you might do that.
  520.  
  521.       While    this approach is expected in most traditional modules,
  522.  
  523.  
  524.  
  525.      Page 8                        (printed 10/23/98)
  526.  
  527.  
  528.  
  529.  
  530.  
  531.  
  532.      PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  533.  
  534.  
  535.  
  536.       it's generally considered rather poor    form in    most object
  537.       modules.  In an object module, you should set    up a
  538.       protective veil to separate interface    from implementation.
  539.       So provide a class method to access class data just as you
  540.       provide object methods to access object data.
  541.  
  542.       So, you _c_o_u_l_d    still keep $Census as a    package    global and
  543.       rely upon others to honor the    contract of the    module and
  544.       therefore not    play around with its implementation.  You
  545.       could    even be    supertricky and    make $Census a tied object as
  546.       described in the _p_e_r_l_t_i_e manpage, thereby intercepting all
  547.       accesses.
  548.  
  549.       But more often than not, you just want to make your class
  550.       data a file-scoped lexical.  To do so, simply    put this at
  551.       the top of the file:
  552.  
  553.           my $Census = 0;
  554.  
  555.       Even though the scope    of a _m_y() normally expires when    the
  556.       block    in which it was    declared is done (in this case the
  557.       whole    file being required or used), Perl's deep binding of
  558.       lexical variables guarantees that the    variable will not be
  559.       deallocated, remaining accessible to functions declared
  560.       within that scope.  This doesn't work    with global variables
  561.       given    temporary values via _l_o_c_a_l(), though.
  562.  
  563.       Irrespective of whether you leave $Census a package global
  564.       or make it instead a file-scoped lexical, you    should make
  565.       these    changes    to your    _P_e_r_s_o_n::_n_e_w() constructor:
  566.  
  567.           sub new {
  568.           my $proto = shift;
  569.           my $class = ref($proto) || $proto;
  570.           my $self  = {};
  571.           $Census++;
  572.           $self->{NAME}      = undef;
  573.           $self->{AGE}      = undef;
  574.           $self->{PEERS}  = [];
  575.           bless    ($self,    $class);
  576.           return $self;
  577.           }
  578.  
  579.           sub population {
  580.           return $Census;
  581.           }
  582.  
  583.       Now that we've done this, we certainly do need a destructor
  584.       so that when Person is destroyed, the    $Census    goes down.
  585.       Here's how this could    be done:
  586.  
  587.           sub DESTROY { --$Census }
  588.  
  589.  
  590.  
  591.      Page 9                        (printed 10/23/98)
  592.  
  593.  
  594.  
  595.  
  596.  
  597.  
  598.      PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  599.  
  600.  
  601.  
  602.       Notice how there's no    memory to deallocate in    the
  603.       destructor?  That's something    that Perl takes    care of    for
  604.       you all by itself.
  605.  
  606.       AAAAcccccccceeeessssssssiiiinnnngggg CCCCllllaaaassssssss DDDDaaaattttaaaa
  607.  
  608.       It turns out that this is not    really a good way to go    about
  609.       handling class data.    A good scalable    rule is    that _y_o_u _m_u_s_t
  610.       _n_e_v_e_r    _r_e_f_e_r_e_n_c_e _c_l_a_s_s    _d_a_t_a _d_i_r_e_c_t_l_y _f_r_o_m _a_n _o_b_j_e_c_t _m_e_t_h_o_d.
  611.       Otherwise you    aren't building    a scalable, inheritable    class.
  612.       The object must be the rendezvous point for all operations,
  613.       especially from an object method.  The globals (class    data)
  614.       would    in some    sense be in the    "wrong"    package    in your
  615.       derived classes.  In Perl, methods execute in    the context of
  616.       the class they were defined in, _n_o_t that of the object that
  617.       triggered them.  Therefore, namespace    visibility of package
  618.       globals in methods is    unrelated to inheritance.
  619.  
  620.       Got that?  Maybe not.     Ok, let's say that some other class
  621.       "borrowed" (well, inherited) the DESTROY method as it    was
  622.       defined above.  When those objects are destroyed, the
  623.       original $Census variable will be altered, not the one in
  624.       the new class's package namespace.  Perhaps this is what you
  625.       want,    but probably it    isn't.
  626.  
  627.       Here's how to    fix this.  We'll store a reference to the data
  628.       in the value accessed    by the hash key    "_CENSUS".  Why    the
  629.       underscore?  Well, mostly because an initial underscore
  630.       already conveys strong feelings of magicalness to a C
  631.       programmer.  It's really just    a mnemonic device to remind
  632.       ourselves that this field is special and not to be used as a
  633.       public data member in    the same way that NAME,    AGE, and PEERS
  634.       are.    (Because we've been developing this code under the
  635.       strict pragma, prior to perl version 5.004 we'll have    to
  636.       quote    the field name.)
  637.  
  638.           sub new {
  639.           my $proto = shift;
  640.           my $class = ref($proto) || $proto;
  641.           my $self  = {};
  642.           $self->{NAME}        = undef;
  643.           $self->{AGE}        = undef;
  644.           $self->{PEERS}    = [];
  645.           # "private" data
  646.           $self->{"_CENSUS"} = \$Census;
  647.           bless    ($self,    $class);
  648.           ++ ${    $self->{"_CENSUS"} };
  649.           return $self;
  650.           }
  651.  
  652.  
  653.  
  654.  
  655.  
  656.  
  657.      Page 10                        (printed 10/23/98)
  658.  
  659.  
  660.  
  661.  
  662.  
  663.  
  664.      PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  665.  
  666.  
  667.  
  668.           sub population {
  669.           my $self = shift;
  670.           if (ref $self) {
  671.               return ${    $self->{"_CENSUS"} };
  672.           } else {
  673.               return $Census;
  674.           }
  675.           }
  676.  
  677.           sub DESTROY {
  678.           my $self = shift;
  679.           -- ${    $self->{"_CENSUS"} };
  680.           }
  681.  
  682.  
  683.       DDDDeeeebbbbuuuuggggggggiiiinnnngggg MMMMeeeetttthhhhooooddddssss
  684.  
  685.       It's common for a class to have a debugging mechanism.  For
  686.       example, you might want to see when objects are created or
  687.       destroyed.  To do that, add a    debugging variable as a    file-
  688.       scoped lexical.  For this, we'll pull    in the standard    Carp
  689.       module to emit our warnings and fatal    messages.  That    way
  690.       messages will    come out with the caller's filename and    line
  691.       number instead of our    own; if    we wanted them to be from our
  692.       own perspective, we'd    just use _d_i_e() and _w_a_r_n() directly
  693.       instead of _c_r_o_a_k() and _c_a_r_p()    respectively.
  694.  
  695.           use Carp;
  696.           my $Debugging = 0;
  697.  
  698.       Now add a new    class method to    access the variable.
  699.  
  700.           sub debug    {
  701.           my $class = shift;
  702.           if (ref $class)  { confess "Class method called as object method" }
  703.           unless (@_ ==    1) { confess "usage: CLASSNAME->debug(level)" }
  704.           $Debugging = shift;
  705.           }
  706.  
  707.       Now fix up DESTROY to    murmur a bit as    the moribund object
  708.       expires:
  709.  
  710.           sub DESTROY {
  711.           my $self = shift;
  712.           if ($Debugging) { carp "Destroying $self " . $self->name }
  713.           -- ${    $self->{"_CENSUS"} };
  714.           }
  715.  
  716.       One could conceivably    make a per-object debug    state.    That
  717.       way you could    call both of these:
  718.  
  719.  
  720.  
  721.  
  722.  
  723.      Page 11                        (printed 10/23/98)
  724.  
  725.  
  726.  
  727.  
  728.  
  729.  
  730.      PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  731.  
  732.  
  733.  
  734.           Person->debug(1);      # entire class
  735.           $him->debug(1);      # just this object
  736.  
  737.       To do    so, we need our    debugging method to be a "bimodal"
  738.       one, one that    works on both classes _a_n_d objects.  Therefore,
  739.       adjust the _d_e_b_u_g() and DESTROY methods as follows:
  740.  
  741.           sub debug    {
  742.           my $self = shift;
  743.           confess "usage: thing->debug(level)"      unless @_ == 1;
  744.           my $level = shift;
  745.           if (ref($self))  {
  746.               $self->{"_DEBUG"}    = $level;      # just myself
  747.           } else {
  748.               $Debugging    = $level;      # whole class
  749.           }
  750.           }
  751.  
  752.           sub DESTROY {
  753.           my $self = shift;
  754.           if ($Debugging || $self->{"_DEBUG"}) {
  755.               carp "Destroying $self " . $self->name;
  756.           }
  757.           -- ${    $self->{"_CENSUS"} };
  758.           }
  759.  
  760.       What happens if a derived class (which we'll call Employee)
  761.       inherits methods from    this Person base class?     Then
  762.       Employee->debug(), when called as a class method,
  763.       manipulates $Person::Debugging not $Employee::Debugging.
  764.  
  765.       CCCCllllaaaassssssss    DDDDeeeessssttttrrrruuuuccccttttoooorrrrssss
  766.  
  767.       The object destructor    handles    the death of each distinct
  768.       object.  But sometimes you want a bit    of cleanup when    the
  769.       entire class is shut down, which currently only happens when
  770.       the program exits.  To make such a _c_l_a_s_s _d_e_s_t_r_u_c_t_o_r, create
  771.       a function in    that class's package named END.     This works
  772.       just like the    END function in    traditional modules, meaning
  773.       that it gets called whenever your program exits unless it
  774.       execs    or dies    of an uncaught signal.    For example,
  775.  
  776.           sub END {
  777.           if ($Debugging) {
  778.               print "All persons are going away    now.\n";
  779.           }
  780.           }
  781.  
  782.       When the program exits, all the class    destructors (END
  783.       functions) are be called in the opposite order that they
  784.       were loaded in (LIFO order).
  785.  
  786.  
  787.  
  788.  
  789.      Page 12                        (printed 10/23/98)
  790.  
  791.  
  792.  
  793.  
  794.  
  795.  
  796.      PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  797.  
  798.  
  799.  
  800.       DDDDooooccccuuuummmmeeeennnnttttiiiinnnngggg tttthhhheeee IIIInnnntttteeeerrrrffffaaaacccceeee
  801.  
  802.       And there you    have it: we've just shown you the
  803.       _i_m_p_l_e_m_e_n_t_a_t_i_o_n of this Person    class.    Its _i_n_t_e_r_f_a_c_e would be
  804.       its documentation.  Usually this means putting it in pod
  805.       ("plain old documentation") format right there in the    same
  806.       file.     In our    Person example,    we would place the following
  807.       docs anywhere    in the Person.pm file.    Even though it looks
  808.       mostly like code, it's not.  It's embedded documentation
  809.       such as would    be used    by the pod2man,    pod2html, or pod2text
  810.       programs.  The Perl compiler ignores pods entirely, just as
  811.       the translators ignore code.    Here's an example of some pods
  812.       describing the informal interface:
  813.  
  814.           =head1 NAME
  815.  
  816.           Person - class to    implement people
  817.  
  818.           =head1 SYNOPSIS
  819.  
  820.            use Person;
  821.  
  822.            #################
  823.            # class methods #
  824.            #################
  825.            $ob    =    Person->new;
  826.            $count =    Person->population;
  827.  
  828.            #######################
  829.            # object    data methods #
  830.            #######################
  831.  
  832.            ### get versions    ###
  833.            $who      = $ob->name;
  834.            $years = $ob->age;
  835.            @pals  = $ob->peers;
  836.  
  837.            ### set versions    ###
  838.            $ob->name("Jason");
  839.            $ob->age(23);
  840.            $ob->peers( "Norbert", "Rhys", "Phineas" );
  841.  
  842.            ########################
  843.            # other object methods #
  844.            ########################
  845.  
  846.            $phrase = $ob->exclaim;
  847.            $ob->happy_birthday;
  848.  
  849.           =head1 DESCRIPTION
  850.  
  851.           The Person class implements dah dee dah dee dah....
  852.  
  853.  
  854.  
  855.      Page 13                        (printed 10/23/98)
  856.  
  857.  
  858.  
  859.  
  860.  
  861.  
  862.      PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  863.  
  864.  
  865.  
  866.       That's all there is to the matter of interface versus
  867.       implementation.  A programmer    who opens up the module    and
  868.       plays    around with all    the private little shiny bits that
  869.       were safely locked up    behind the interface contract has
  870.       voided the warranty, and you shouldn't worry about their
  871.       fate.
  872.  
  873.      AAAAggggggggrrrreeeeggggaaaattttiiiioooonnnn
  874.       Suppose you later want to change the class to    implement
  875.       better names.     Perhaps you'd like to support both given
  876.       names    (called    Christian names, irrespective of one's
  877.       religion) and    family names (called surnames),    plus nicknames
  878.       and titles.  If users    of your    Person class have been
  879.       properly accessing it    through    its documented interface, then
  880.       you can easily change    the underlying implementation.    If
  881.       they haven't,    then they lose and it's    their fault for
  882.       breaking the contract    and voiding their warranty.
  883.  
  884.       To do    this, we'll make another class,    this one called
  885.       Fullname.  What's the    Fullname class look like?  To answer
  886.       that question, you have to first figure out how you want to
  887.       use it.  How about we    use it this way:
  888.  
  889.           $him = Person->new();
  890.           $him->fullname->title("St");
  891.           $him->fullname->christian("Thomas");
  892.           $him->fullname->surname("Aquinas");
  893.           $him->fullname->nickname("Tommy");
  894.           printf "His normal name is %s\n",    $him->name;
  895.           printf "But his real name    is %s\n", $him->fullname->as_string;
  896.  
  897.       Ok.  To do this, we'll change    _P_e_r_s_o_n::_n_e_w() so that it
  898.       supports a full name field this way:
  899.  
  900.           sub new {
  901.           my $proto = shift;
  902.           my $class = ref($proto) || $proto;
  903.           my $self  = {};
  904.           $self->{FULLNAME} = Fullname->new();
  905.           $self->{AGE}        = undef;
  906.           $self->{PEERS}    = [];
  907.           $self->{"_CENSUS"} = \$Census;
  908.           bless    ($self,    $class);
  909.           ++ ${    $self->{"_CENSUS"} };
  910.           return $self;
  911.           }
  912.  
  913.           sub fullname {
  914.           my $self = shift;
  915.           return $self->{FULLNAME};
  916.           }
  917.  
  918.  
  919.  
  920.  
  921.      Page 14                        (printed 10/23/98)
  922.  
  923.  
  924.  
  925.  
  926.  
  927.  
  928.      PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  929.  
  930.  
  931.  
  932.       Then to support old code, define _P_e_r_s_o_n::_n_a_m_e() this way:
  933.  
  934.           sub name {
  935.           my $self = shift;
  936.           return $self->{FULLNAME}->nickname(@_)
  937.             ||     $self->{FULLNAME}->christian(@_);
  938.           }
  939.  
  940.       Here's the Fullname class.  We'll use    the same technique of
  941.       using    a hash reference to hold data fields, and methods by
  942.       the appropriate name to access them:
  943.  
  944.           package Fullname;
  945.           use strict;
  946.  
  947.           sub new {
  948.           my $proto = shift;
  949.           my $class = ref($proto) || $proto;
  950.           my $self  = {
  951.               TITLE      => undef,
  952.               CHRISTIAN      => undef,
  953.               SURNAME      => undef,
  954.               NICK      => undef,
  955.           };
  956.           bless    ($self,    $class);
  957.           return $self;
  958.           }
  959.  
  960.           sub christian {
  961.           my $self = shift;
  962.           if (@_) { $self->{CHRISTIAN} = shift }
  963.           return $self->{CHRISTIAN};
  964.           }
  965.  
  966.           sub surname {
  967.           my $self = shift;
  968.           if (@_) { $self->{SURNAME} = shift }
  969.           return $self->{SURNAME};
  970.           }
  971.  
  972.           sub nickname {
  973.           my $self = shift;
  974.           if (@_) { $self->{NICK} = shift }
  975.           return $self->{NICK};
  976.           }
  977.  
  978.           sub title    {
  979.           my $self = shift;
  980.           if (@_) { $self->{TITLE} = shift }
  981.           return $self->{TITLE};
  982.           }
  983.  
  984.  
  985.  
  986.  
  987.      Page 15                        (printed 10/23/98)
  988.  
  989.  
  990.  
  991.  
  992.  
  993.  
  994.      PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  995.  
  996.  
  997.  
  998.           sub as_string {
  999.           my $self = shift;
  1000.           my $name = join(" ", @$self{'CHRISTIAN', 'SURNAME'});
  1001.           if ($self->{TITLE}) {
  1002.               $name = $self->{TITLE} . " " . $name;
  1003.           }
  1004.           return $name;
  1005.           }
  1006.  
  1007.           1;
  1008.  
  1009.       Finally, here's the test program:
  1010.  
  1011.           #!/usr/bin/perl -w
  1012.           use strict;
  1013.           use Person;
  1014.           sub END {    show_census() }
  1015.  
  1016.           sub show_census ()  {
  1017.           printf "Current population: %d\n", Person->population;
  1018.           }
  1019.  
  1020.           Person->debug(1);
  1021.  
  1022.           show_census();
  1023.  
  1024.           my $him =    Person->new();
  1025.  
  1026.           $him->fullname->christian("Thomas");
  1027.           $him->fullname->surname("Aquinas");
  1028.           $him->fullname->nickname("Tommy");
  1029.           $him->fullname->title("St");
  1030.           $him->age(1);
  1031.  
  1032.           printf "%s is really %s.\n", $him->name, $him->fullname;
  1033.           printf "%s's age:    %d.\n",    $him->name, $him->age;
  1034.           $him->happy_birthday;
  1035.           printf "%s's age:    %d.\n",    $him->name, $him->age;
  1036.  
  1037.           show_census();
  1038.  
  1039.  
  1040.      IIIInnnnhhhheeeerrrriiiittttaaaannnncccceeee
  1041.       Object-oriented programming systems all support some notion
  1042.       of inheritance.  Inheritance means allowing one class    to
  1043.       piggy-back on    top of another one so you don't    have to    write
  1044.       the same code    again and again.  It's about software reuse,
  1045.       and therefore    related    to Laziness, the principal virtue of a
  1046.       programmer.  (The import/export mechanisms in    traditional
  1047.       modules are also a form of code reuse, but a simpler one
  1048.       than the true    inheritance that you find in object modules.)
  1049.  
  1050.  
  1051.  
  1052.  
  1053.      Page 16                        (printed 10/23/98)
  1054.  
  1055.  
  1056.  
  1057.  
  1058.  
  1059.  
  1060.      PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  1061.  
  1062.  
  1063.  
  1064.       Sometimes the    syntax of inheritance is built into the    core
  1065.       of the language, and sometimes it's not.  Perl has no
  1066.       special syntax for specifying    the class (or classes) to
  1067.       inherit from.     Instead, it's all strictly in the semantics.
  1068.       Each package can have    a variable called @ISA,    which governs
  1069.       (method) inheritance.     If you    try to call a method on    an
  1070.       object or class, and that method is not found    in that
  1071.       object's package, Perl then looks to @ISA for    other packages
  1072.       to go    looking    through    in search of the missing method.
  1073.  
  1074.       Like the special per-package variables recognized by
  1075.       Exporter (such as @EXPORT, @EXPORT_OK, @EXPORT_FAIL,
  1076.       %EXPORT_TAGS,    and $VERSION), the @ISA    array _m_u_s_t be a
  1077.       package-scoped global    and not    a file-scoped lexical created
  1078.       via _m_y().  Most classes have just one    item in    their @ISA
  1079.       array.  In this case,    we have    what's called "single
  1080.       inheritance",    or SI for short.
  1081.  
  1082.       Consider this    class:
  1083.  
  1084.           package Employee;
  1085.           use Person;
  1086.           @ISA = ("Person");
  1087.           1;
  1088.  
  1089.       Not a    lot to it, eh?    All it's doing so far is loading in
  1090.       another class    and stating that this one will inherit methods
  1091.       from that other class    if need    be.  We    have given it none of
  1092.       its own methods.  We rely upon an Employee to    behave just
  1093.       like a Person.
  1094.  
  1095.       Setting up an    empty class like this is called    the "empty
  1096.       subclass test"; that is, making a derived class that does
  1097.       nothing but inherit from a base class.  If the original base
  1098.       class    has been designed properly, then the new derived class
  1099.       can be used as a drop-in replacement for the old one.     This
  1100.       means    you should be able to write a program like this:
  1101.  
  1102.           use Employee;
  1103.           my $empl = Employee->new();
  1104.           $empl->name("Jason");
  1105.           $empl->age(23);
  1106.           printf "%s is age    %d.\n",    $empl->name, $empl->age;
  1107.  
  1108.       By proper design, we mean always using the two-argument form
  1109.       of _b_l_e_s_s(), avoiding direct access of    global data, and not
  1110.       exporting anything.  If you look back    at the _P_e_r_s_o_n::_n_e_w()
  1111.       function we defined above, we    were careful to    do that.
  1112.       There's a bit    of package data    used in    the constructor, but
  1113.       the reference    to this    is stored on the object    itself and all
  1114.       other    methods    access package data via    that reference,    so we
  1115.       should be ok.
  1116.  
  1117.  
  1118.  
  1119.      Page 17                        (printed 10/23/98)
  1120.  
  1121.  
  1122.  
  1123.  
  1124.  
  1125.  
  1126.      PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  1127.  
  1128.  
  1129.  
  1130.       What do we mean by the _P_e_r_s_o_n::_n_e_w() function    -- isn't that
  1131.       actually a method?  Well, in principle, yes.    A method is
  1132.       just a function that expects as its first argument a class
  1133.       name (package) or object (blessed reference).
  1134.       _P_e_r_s_o_n::_n_e_w()    is the function    that both the Person->new()
  1135.       method and the Employee->new() method    end up calling.
  1136.       Understand that while    a method call looks a lot like a
  1137.       function call, they aren't really quite the same, and    if you
  1138.       treat    them as    the same, you'll very soon be left with
  1139.       nothing but broken programs.    First, the actual underlying
  1140.       calling conventions are different: method calls get an extra
  1141.       argument.  Second, function calls don't do inheritance, but
  1142.       methods do.
  1143.  
  1144.           Method Call          Resulting Function Call
  1145.           -----------          ------------------------
  1146.           Person->new()          Person::new("Person")
  1147.           Employee->new()      Person::new("Employee")
  1148.  
  1149.       So don't use function    calls when you mean to call a method.
  1150.  
  1151.       If an    employee is just a Person, that's not all too very
  1152.       interesting.    So let's add some other    methods.  We'll    give
  1153.       our employee data fields to access their salary, their
  1154.       employee ID, and their start date.
  1155.  
  1156.       If you're getting a little tired of creating all these
  1157.       nearly identical methods just    to get at the object's data,
  1158.       do not despair.  Later, we'll    describe several different
  1159.       convenience mechanisms for shortening    this up.  Meanwhile,
  1160.       here's the straight-forward way:
  1161.  
  1162.           sub salary {
  1163.           my $self = shift;
  1164.           if (@_) { $self->{SALARY} = shift }
  1165.           return $self->{SALARY};
  1166.           }
  1167.  
  1168.           sub id_number {
  1169.           my $self = shift;
  1170.           if (@_) { $self->{ID}    = shift    }
  1171.           return $self->{ID};
  1172.           }
  1173.  
  1174.           sub start_date {
  1175.           my $self = shift;
  1176.           if (@_) { $self->{START_DATE}    = shift    }
  1177.           return $self->{START_DATE};
  1178.           }
  1179.  
  1180.  
  1181.  
  1182.  
  1183.  
  1184.  
  1185.      Page 18                        (printed 10/23/98)
  1186.  
  1187.  
  1188.  
  1189.  
  1190.  
  1191.  
  1192.      PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  1193.  
  1194.  
  1195.  
  1196.       OOOOvvvveeeerrrrrrrriiiiddddddddeeeennnn MMMMeeeetttthhhhooooddddssss
  1197.  
  1198.       What happens when both a derived class and its base class
  1199.       have the same    method defined?     Well, then you    get the
  1200.       derived class's version of that method.  For example,    let's
  1201.       say that we want the _p_e_e_r_s() method called on    an employee to
  1202.       act a    bit differently.  Instead of just returning the    list
  1203.       of peer names, let's return slightly different strings.  So
  1204.       doing    this:
  1205.  
  1206.           $empl->peers("Peter", "Paul", "Mary");
  1207.           printf "His peers    are: %s\n", join(", ", $empl->peers);
  1208.  
  1209.       will produce:
  1210.  
  1211.           His peers    are: PEON=PETER, PEON=PAUL, PEON=MARY
  1212.  
  1213.       To do    this, merely add this definition into the Employee.pm
  1214.       file:
  1215.  
  1216.           sub peers    {
  1217.           my $self = shift;
  1218.           if (@_) { @{ $self->{PEERS} }    = @_ }
  1219.           return map { "PEON=\U$_" } @{    $self->{PEERS} };
  1220.           }
  1221.  
  1222.       There, we've just demonstrated the high-falutin' concept
  1223.       known    in certain circles as _p_o_l_y_m_o_r_p_h_i_s_m.  We've taken on
  1224.       the form and behaviour of an existing    object,    and then we've
  1225.       altered it to    suit our own purposes.    This is    a form of
  1226.       Laziness.  (Getting polymorphed is also what happens when
  1227.       the wizard decides you'd look    better as a frog.)
  1228.  
  1229.       Every    now and    then you'll want to have a method call trigger
  1230.       both its derived class (also known as    "subclass") version as
  1231.       well as its base class (also known as    "superclass") version.
  1232.       In practice, constructors and    destructors are    likely to want
  1233.       to do    this, and it probably also makes sense in the _d_e_b_u_g()
  1234.       method we showed previously.
  1235.  
  1236.       To do    this, add this to Employee.pm:
  1237.  
  1238.           use Carp;
  1239.           my $Debugging = 0;
  1240.  
  1241.  
  1242.  
  1243.  
  1244.  
  1245.  
  1246.  
  1247.  
  1248.  
  1249.  
  1250.  
  1251.      Page 19                        (printed 10/23/98)
  1252.  
  1253.  
  1254.  
  1255.  
  1256.  
  1257.  
  1258.      PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  1259.  
  1260.  
  1261.  
  1262.           sub debug    {
  1263.           my $self = shift;
  1264.           confess "usage: thing->debug(level)"      unless @_ == 1;
  1265.           my $level = shift;
  1266.           if (ref($self))  {
  1267.               $self->{"_DEBUG"}    = $level;
  1268.           } else {
  1269.               $Debugging = $level;          #    whole class
  1270.           }
  1271.           Person::debug($self, $Debugging);   #    don't really do    this
  1272.           }
  1273.  
  1274.       As you see, we turn around and call the Person package's
  1275.       _d_e_b_u_g() function.  But this is far too fragile for good
  1276.       design.  What    if Person doesn't have a _d_e_b_u_g() function, but
  1277.       is inheriting    _i_t_s _d_e_b_u_g() method from    elsewhere?  It would
  1278.       have been slightly better to say
  1279.  
  1280.           Person->debug($Debugging);
  1281.  
  1282.       But even that's got too much hard-coded.  It's somewhat
  1283.       better to say
  1284.  
  1285.           $self->Person::debug($Debugging);
  1286.  
  1287.       Which    is a funny way to say to start looking for a _d_e_b_u_g()
  1288.       method up in Person.    This strategy is more often seen on
  1289.       overridden object methods than on overridden class methods.
  1290.  
  1291.       There    is still something a bit off here.  We've hard-coded
  1292.       our superclass's name.  This in particular is    bad if you
  1293.       change which classes you inherit from, or add    others.
  1294.       Fortunately, the pseudoclass SUPER comes to the rescue here.
  1295.  
  1296.           $self->SUPER::debug($Debugging);
  1297.  
  1298.       This way it starts looking in    my class's @ISA.  This only
  1299.       makes    sense from _w_i_t_h_i_n a method call, though.  Don't    try to
  1300.       access anything in SUPER:: from anywhere else, because it
  1301.       doesn't exist    outside    an overridden method call.
  1302.  
  1303.       Things are getting a bit complicated here.  Have we done
  1304.       anything we shouldn't?  As before, one way to    test whether
  1305.       we're    designing a decent class is via    the empty subclass
  1306.       test.     Since we already have an Employee class that we're
  1307.       trying to check, we'd    better get a new empty subclass    that
  1308.       can derive from Employee.  Here's one:
  1309.  
  1310.           package Boss;
  1311.           use Employee;       # :-)
  1312.           @ISA = qw(Employee);
  1313.  
  1314.  
  1315.  
  1316.  
  1317.      Page 20                        (printed 10/23/98)
  1318.  
  1319.  
  1320.  
  1321.  
  1322.  
  1323.  
  1324.      PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  1325.  
  1326.  
  1327.  
  1328.       And here's the test program:
  1329.  
  1330.           #!/usr/bin/perl -w
  1331.           use strict;
  1332.           use Boss;
  1333.           Boss->debug(1);
  1334.  
  1335.           my $boss = Boss->new();
  1336.  
  1337.           $boss->fullname->title("Don");
  1338.           $boss->fullname->surname("Pichon Alvarez");
  1339.           $boss->fullname->christian("Federico Jesus");
  1340.           $boss->fullname->nickname("Fred");
  1341.  
  1342.           $boss->age(47);
  1343.           $boss->peers("Frank", "Felipe", "Faust");
  1344.  
  1345.           printf "%s is age    %d.\n",    $boss->fullname, $boss->age;
  1346.           printf "His peers    are: %s\n", join(", ", $boss->peers);
  1347.  
  1348.       Running it, we see that we're    still ok.  If you'd like to
  1349.       dump out your    object in a nice format, somewhat like the way
  1350.       the 'x' command works    in the debugger, you could use the
  1351.       Data::Dumper module from CPAN    this way:
  1352.  
  1353.           use Data::Dumper;
  1354.           print "Here's the    boss:\n";
  1355.           print Dumper($boss);
  1356.  
  1357.       Which    shows us something like    this:
  1358.  
  1359.           Here's the boss:
  1360.           $VAR1 = bless( {
  1361.            _CENSUS => \1,
  1362.            FULLNAME => bless( {
  1363.                     TITLE => 'Don',
  1364.                     SURNAME    => 'Pichon Alvarez',
  1365.                     NICK =>    'Fred',
  1366.                     CHRISTIAN => 'Federico Jesus'
  1367.                       }, 'Fullname' ),
  1368.            AGE => 47,
  1369.            PEERS => [
  1370.                   'Frank',
  1371.                   'Felipe',
  1372.                   'Faust'
  1373.                 ]
  1374.          }, 'Boss' );
  1375.  
  1376.       Hm.... something's missing there.  What about    the salary,
  1377.       start    date, and ID fields?  Well, we never set them to
  1378.       anything, even undef,    so they    don't show up in the hash's
  1379.       keys.     The Employee class has    no _n_e_w() method    of its own,
  1380.  
  1381.  
  1382.  
  1383.      Page 21                        (printed 10/23/98)
  1384.  
  1385.  
  1386.  
  1387.  
  1388.  
  1389.  
  1390.      PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  1391.  
  1392.  
  1393.  
  1394.       and the _n_e_w()    method in Person doesn't know about Employees.
  1395.       (Nor should it: proper OO design dictates that a subclass be
  1396.       allowed to know about    its immediate superclass, but never
  1397.       vice-versa.)    So let's fix up    _E_m_p_l_o_y_e_e::_n_e_w()    this way:
  1398.  
  1399.           sub new {
  1400.           my $proto = shift;
  1401.           my $class = ref($proto) || $proto;
  1402.           my $self  = $class->SUPER::new();
  1403.           $self->{SALARY}     = undef;
  1404.           $self->{ID}         = undef;
  1405.           $self->{START_DATE}     = undef;
  1406.           bless    ($self,    $class);      # reconsecrate
  1407.           return $self;
  1408.           }
  1409.  
  1410.       Now if you dump out an Employee or Boss object, you'll find
  1411.       that new fields show up there    now.
  1412.  
  1413.       MMMMuuuullllttttiiiipppplllleeee IIIInnnnhhhheeeerrrriiiittttaaaannnncccceeee
  1414.  
  1415.       Ok, at the risk of confusing beginners and annoying OO
  1416.       gurus, it's time to confess that Perl's object system
  1417.       includes that    controversial notion known as multiple
  1418.       inheritance, or MI for short.     All this means    is that    rather
  1419.       than having just one parent class who    in turn    might itself
  1420.       have a parent    class, etc., that you can directly inherit
  1421.       from two or more parents.  It's true that some uses of MI
  1422.       can get you into trouble, although hopefully not quite so
  1423.       much trouble with Perl as with dubiously-OO languages    like
  1424.       C++.
  1425.  
  1426.       The way it works is actually pretty simple: just put more
  1427.       than one package name    in your    @ISA array.  When it comes
  1428.       time for Perl    to go finding methods for your object, it
  1429.       looks    at each    of these packages in order.  Well, kinda.
  1430.       It's actually    a fully    recursive, depth-first order.
  1431.       Consider a bunch of @ISA arrays like this:
  1432.  
  1433.           @First::ISA    = qw( Alpha );
  1434.           @Second::ISA   = qw( Beta    );
  1435.           @Third::ISA    = qw( First Second    );
  1436.  
  1437.       If you have an object    of class Third:
  1438.  
  1439.           my $ob = Third->new();
  1440.           $ob->spin();
  1441.  
  1442.       How do we find a _s_p_i_n() method (or a _n_e_w() method for    that
  1443.       matter)?  Because the    search is depth-first, classes will be
  1444.       looked up in the following order: Third, First, Alpha,
  1445.       Second, and Beta.
  1446.  
  1447.  
  1448.  
  1449.      Page 22                        (printed 10/23/98)
  1450.  
  1451.  
  1452.  
  1453.  
  1454.  
  1455.  
  1456.      PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  1457.  
  1458.  
  1459.  
  1460.       In practice, few class modules have been seen    that actually
  1461.       make use of MI.  One nearly always chooses simple
  1462.       containership    of one class within another over MI.  That's
  1463.       why our Person object    _c_o_n_t_a_i_n_e_d a Fullname object.  That
  1464.       doesn't mean it _w_a_s one.
  1465.  
  1466.       However, there is one    particular area    where MI in Perl is
  1467.       rampant:  borrowing another class's class methods.  This is
  1468.       rather common, especially with some bundled "objectless"
  1469.       classes, like    Exporter, DynaLoader, AutoLoader, and
  1470.       SelfLoader.  These classes do    not provide constructors; they
  1471.       exist    only so    you may    inherit    their class methods.  (It's
  1472.       not entirely clear why inheritance was done here rather than
  1473.       traditional module importation.)
  1474.  
  1475.       For example, here is the POSIX module's @ISA:
  1476.  
  1477.           package POSIX;
  1478.           @ISA = qw(Exporter DynaLoader);
  1479.  
  1480.       The POSIX module isn't really    an object module, but then,
  1481.       neither are Exporter or DynaLoader.  They're just lending
  1482.       their    classes' behaviours to POSIX.
  1483.  
  1484.       Why don't people use MI for object methods much?  One    reason
  1485.       is that it can have complicated side-effects.     For one
  1486.       thing, your inheritance graph    (no longer a tree) might
  1487.       converge back    to the same base class.     Although Perl guards
  1488.       against recursive inheritance, merely    having parents who are
  1489.       related to each other    via a common ancestor, incestuous
  1490.       though it sounds, is not forbidden.  What if in our Third
  1491.       class    shown above we wanted its _n_e_w()    method to also call
  1492.       both overridden constructors in its two parent classes?  The
  1493.       SUPER    notation would only find the first one.     Also, what
  1494.       about    if the Alpha and Beta classes both had a common
  1495.       ancestor, like Nought?  If you kept climbing up the
  1496.       inheritance tree calling overridden methods, you'd end up
  1497.       calling _N_o_u_g_h_t::_n_e_w()    twice, which might well    be a bad idea.
  1498.  
  1499.       UUUUNNNNIIIIVVVVEEEERRRRSSSSAAAALLLL:::: TTTThhhheeee RRRRooooooootttt ooooffff AAAAllllllll OOOObbbbjjjjeeeeccccttttssss
  1500.  
  1501.       Wouldn't it be convenient if all objects were    rooted at some
  1502.       ultimate base    class?    That way you could give    every object
  1503.       common methods without having    to go and add it to each and
  1504.       every    @ISA.  Well, it    turns out that you can.     You don't see
  1505.       it, but Perl tacitly and irrevocably assumes that there's an
  1506.       extra    element    at the end of @ISA: the    class UNIVERSAL.  In
  1507.       version 5.003, there were no predefined methods there, but
  1508.       you could put    whatever you felt like into it.
  1509.  
  1510.       However, as of version 5.004 (or some    subversive releases,
  1511.       like 5.003_08), UNIVERSAL has    some methods in    it already.
  1512.  
  1513.  
  1514.  
  1515.      Page 23                        (printed 10/23/98)
  1516.  
  1517.  
  1518.  
  1519.  
  1520.  
  1521.  
  1522.      PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  1523.  
  1524.  
  1525.  
  1526.       These    are builtin to your Perl binary, so they don't take
  1527.       any extra time to load.  Predefined methods include _i_s_a(),
  1528.       _c_a_n(), and _V_E_R_S_I_O_N().     _i_s_a() tells you whether an object or
  1529.       class    "is" another one without having    to traverse the
  1530.       hierarchy yourself:
  1531.  
  1532.          $has_io = $fd->isa("IO::Handle");
  1533.          $itza_handle = IO::Socket->isa("IO::Handle");
  1534.  
  1535.       The _c_a_n() method, called against that    object or class,
  1536.       reports back whether its string argument is a    callable
  1537.       method name in that class.  In fact, it gives    you back a
  1538.       function reference to    that method:
  1539.  
  1540.          $his_print_method = $obj->can('as_string');
  1541.  
  1542.       Finally, the VERSION method checks whether the class (or the
  1543.       object's class) has a    package    global called $VERSION that's
  1544.       high enough, as in:
  1545.  
  1546.           Some_Module->VERSION(3.0);
  1547.           $his_vers    = $ob->VERSION();
  1548.  
  1549.       However, we don't usually call VERSION ourselves.  (Remember
  1550.       that an all uppercase    function name is a Perl    convention
  1551.       that indicates that the function will    be automatically used
  1552.       by Perl in some way.)     In this case, it happens when you say
  1553.  
  1554.           use Some_Module 3.0;
  1555.  
  1556.       If you wanted    to add version checking    to your    Person class
  1557.       explained above, just    add this to Person.pm:
  1558.  
  1559.           use vars qw($VERSION);
  1560.           $VERSION = '1.1';
  1561.  
  1562.       and then in Employee.pm could    you can    say
  1563.  
  1564.           use Employee 1.1;
  1565.  
  1566.       And it would make sure that you have at least    that version
  1567.       number or higher available.    This is    not the    same as
  1568.       loading in that exact    version    number.     No mechanism
  1569.       currently exists for concurrent installation of multiple
  1570.       versions of a    module.     Lamentably.
  1571.  
  1572.      AAAAlllltttteeeerrrrnnnnaaaatttteeee OOOObbbbjjjjeeeecccctttt RRRReeeepppprrrreeeesssseeeennnnttttaaaattttiiiioooonnnnssss
  1573.       Nothing requires objects to be implemented as    hash
  1574.       references.  An object can be    any sort of reference so long
  1575.       as its referent has been suitably blessed.  That means
  1576.       scalar, array, and code references are also fair game.
  1577.  
  1578.  
  1579.  
  1580.  
  1581.      Page 24                        (printed 10/23/98)
  1582.  
  1583.  
  1584.  
  1585.  
  1586.  
  1587.  
  1588.      PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  1589.  
  1590.  
  1591.  
  1592.       A scalar would work if the object has    only one datum to
  1593.       hold.     An array would    work for most cases, but makes
  1594.       inheritance a    bit dodgy because you have to invent new
  1595.       indices for the derived classes.
  1596.  
  1597.       AAAArrrrrrrraaaayyyyssss aaaassss OOOObbbbjjjjeeeeccccttttssss
  1598.  
  1599.       If the user of your class honors the contract    and sticks to
  1600.       the advertised interface, then you can change    its underlying
  1601.       interface if you feel    like it.  Here's another
  1602.       implementation that conforms to the same interface
  1603.       specification.  This time we'll use an array reference
  1604.       instead of a hash reference to represent the object.
  1605.  
  1606.           package Person;
  1607.           use strict;
  1608.  
  1609.           my($NAME,    $AGE, $PEERS) =    ( 0 .. 2 );
  1610.  
  1611.           ############################################
  1612.           ## the object constructor    (array version)    ##
  1613.           ############################################
  1614.           sub new {
  1615.           my $self = [];
  1616.           $self->[$NAME]   = undef;  # this is unnecessary
  1617.           $self->[$AGE]       = undef;  # as is this
  1618.           $self->[$PEERS]  = [];     # but this    isn't, really
  1619.           bless($self);
  1620.           return $self;
  1621.           }
  1622.  
  1623.           sub name {
  1624.           my $self = shift;
  1625.           if (@_) { $self->[$NAME] = shift }
  1626.           return $self->[$NAME];
  1627.           }
  1628.  
  1629.           sub age {
  1630.           my $self = shift;
  1631.           if (@_) { $self->[$AGE] = shift }
  1632.           return $self->[$AGE];
  1633.           }
  1634.  
  1635.           sub peers    {
  1636.           my $self = shift;
  1637.           if (@_) { @{ $self->[$PEERS] } = @_ }
  1638.           return @{ $self->[$PEERS] };
  1639.           }
  1640.  
  1641.           1;  # so the require or use succeeds
  1642.  
  1643.       You might guess that the array access    would be a lot faster
  1644.  
  1645.  
  1646.  
  1647.      Page 25                        (printed 10/23/98)
  1648.  
  1649.  
  1650.  
  1651.  
  1652.  
  1653.  
  1654.      PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  1655.  
  1656.  
  1657.  
  1658.       than the hash    access,    but they're actually comparable.  The
  1659.       array    is a _l_i_t_t_l_e bit    faster,    but not    more than ten or
  1660.       fifteen percent, even    when you replace the variables above
  1661.       like $AGE with literal numbers, like 1.  A bigger difference
  1662.       between the two approaches can be found in memory use.  A
  1663.       hash representation takes up more memory than    an array
  1664.       representation because you have to allocate memory for the
  1665.       keys as well as for the values.  However, it really isn't
  1666.       that bad, especially since as    of version 5.004, memory is
  1667.       only allocated once for a given hash key, no matter how many
  1668.       hashes have that key.     It's expected that sometime in    the
  1669.       future, even these differences will fade into    obscurity as
  1670.       more efficient underlying representations are    devised.
  1671.  
  1672.       Still, the tiny edge in speed    (and somewhat larger one in
  1673.       memory) is enough to make some programmers choose an array
  1674.       representation for simple classes.  There's still a little
  1675.       problem with scalability, though, because later in life when
  1676.       you feel like    creating subclasses, you'll find that hashes
  1677.       just work out    better.
  1678.  
  1679.       CCCClllloooossssuuuurrrreeeessss aaaassss OOOObbbbjjjjeeeeccccttttssss
  1680.  
  1681.       Using    a code reference to represent an object    offers some
  1682.       fascinating possibilities.  We can create a new anonymous
  1683.       function (closure) who alone in all the world    can see    the
  1684.       object's data.  This is because we put the data into an
  1685.       anonymous hash that's    lexically visible only to the closure
  1686.       we create, bless, and    return as the object.  This object's
  1687.       methods turn around and call the closure as a    regular
  1688.       subroutine call, passing it the field    we want    to affect.
  1689.       (Yes,    the double-function call is slow, but if you wanted
  1690.       fast,    you wouldn't be    using objects at all, eh? :-)
  1691.  
  1692.       Use would be similar to before:
  1693.  
  1694.           use Person;
  1695.           $him = Person->new();
  1696.           $him->name("Jason");
  1697.           $him->age(23);
  1698.           $him->peers( [ "Norbert",    "Rhys",    "Phineas" ] );
  1699.           printf "%s is %d years old.\n", $him->name, $him->age;
  1700.           print "His peers are: ", join(", ", @{$him->peers}), "\n";
  1701.  
  1702.       but the implementation would be radically, perhaps even
  1703.       sublimely different:
  1704.  
  1705.           package Person;
  1706.  
  1707.  
  1708.  
  1709.  
  1710.  
  1711.  
  1712.  
  1713.      Page 26                        (printed 10/23/98)
  1714.  
  1715.  
  1716.  
  1717.  
  1718.  
  1719.  
  1720.      PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  1721.  
  1722.  
  1723.  
  1724.           sub new {
  1725.            my $that  = shift;
  1726.            my $class = ref($that) || $that;
  1727.            my $self = {
  1728.               NAME  => undef,
  1729.               AGE   => undef,
  1730.               PEERS => [],
  1731.            };
  1732.            my $closure = sub {
  1733.               my $field    = shift;
  1734.               if (@_) {    $self->{$field}    = shift    }
  1735.               return    $self->{$field};
  1736.           };
  1737.           bless($closure, $class);
  1738.           return $closure;
  1739.           }
  1740.  
  1741.           sub name     { &{ $_[0] }("NAME",  @_[ 1 ..    $#_ ] )    }
  1742.           sub age     { &{ $_[0] }("AGE",   @_[ 1 ..    $#_ ] )    }
  1743.           sub peers     { &{ $_[0] }("PEERS", @_[ 1 ..    $#_ ] )    }
  1744.  
  1745.           1;
  1746.  
  1747.       Because this object is hidden    behind a code reference, it's
  1748.       probably a bit mysterious to those whose background is more
  1749.       firmly rooted    in standard procedural or object-based
  1750.       programming languages    than in    functional programming
  1751.       languages whence closures derive.  The object    created    and
  1752.       returned by the _n_e_w()    method is itself not a data reference
  1753.       as we've seen    before.     It's an anonymous code    reference that
  1754.       has within it    access to a specific version (lexical binding
  1755.       and instantiation) of    the object's data, which are stored in
  1756.       the private variable $self.  Although    this is    the same
  1757.       function each    time, it contains a different version of
  1758.       $self.
  1759.  
  1760.       When a method    like $him->name("Jason") is called, its
  1761.       implicit zeroth argument is the invoking object--just    as it
  1762.       is with all method calls.  But in this case, it's our    code
  1763.       reference (something like a function pointer in C++, but
  1764.       with deep binding of lexical variables).  There's not    a lot
  1765.       to be    done with a code reference beyond calling it, so
  1766.       that's just what we do when we say &{$_[0]}.    This is    just a
  1767.       regular function call, not a method call.  The initial
  1768.       argument is the string "NAME", and any remaining arguments
  1769.       are whatever had been    passed to the method itself.
  1770.  
  1771.       Once we're executing inside the closure that had been
  1772.       created in _n_e_w(), the    $self hash reference suddenly becomes
  1773.       visible.  The    closure    grabs its first    argument ("NAME" in
  1774.       this case because that's what    the _n_a_m_e() method passed it),
  1775.       and uses that    string to subscript into the private hash
  1776.  
  1777.  
  1778.  
  1779.      Page 27                        (printed 10/23/98)
  1780.  
  1781.  
  1782.  
  1783.  
  1784.  
  1785.  
  1786.      PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  1787.  
  1788.  
  1789.  
  1790.       hidden in its    unique version of $self.
  1791.  
  1792.       Nothing under    the sun    will allow anyone outside the
  1793.       executing method to be able to get at    this hidden data.
  1794.       Well,    nearly nothing.     You _c_o_u_l_d single step through the
  1795.       program using    the debugger and find out the pieces while
  1796.       you're in the    method,    but everyone else is out of luck.
  1797.  
  1798.       There, if that doesn't excite    the Scheme folks, then I just
  1799.       don't    know what will.     Translation of    this technique into
  1800.       C++, Java, or    any other braindead-static language is left as
  1801.       a futile exercise for    aficionados of those camps.
  1802.  
  1803.       You could even add a bit of nosiness via the _c_a_l_l_e_r()
  1804.       function and make the    closure    refuse to operate unless
  1805.       called via its own package.  This would no doubt satisfy
  1806.       certain fastidious concerns of programming police and
  1807.       related puritans.
  1808.  
  1809.       If you were wondering    when Hubris, the third principle
  1810.       virtue of a programmer, would    come into play,    here you have
  1811.       it. (More seriously, Hubris is just the pride    in
  1812.       craftsmanship    that comes from    having written a sound bit of
  1813.       well-designed    code.)
  1814.  
  1815.      AAAAUUUUTTTTOOOOLLLLOOOOAAAADDDD:::: PPPPrrrrooooxxxxyyyy MMMMeeeetttthhhhooooddddssss
  1816.       Autoloading is a way to intercept calls to undefined
  1817.       methods.  An autoload    routine    may choose to create a new
  1818.       function on the fly, either loaded from disk or perhaps just
  1819.       _e_v_a_l()ed right there.     This define-on-the-fly    strategy is
  1820.       why it's called autoloading.
  1821.  
  1822.       But that's only one possible approach.  Another one is to
  1823.       just have the    autoloaded method itself directly provide the
  1824.       requested service.  When used    in this    way, you may think of
  1825.       autoloaded methods as    "proxy"    methods.
  1826.  
  1827.       When Perl tries to call an undefined function    in a
  1828.       particular package and that function is not defined, it
  1829.       looks    for a function in that same package called AUTOLOAD.
  1830.       If one exists, it's called with the same arguments as    the
  1831.       original function would have had.  The fully-qualified name
  1832.       of the function is stored in that package's global variable
  1833.       $AUTOLOAD.  Once called, the function    can do anything    it
  1834.       would    like, including    defining a new function    by the right
  1835.       name,    and then doing a really    fancy kind of goto right to
  1836.       it, erasing itself from the call stack.
  1837.  
  1838.       What does this have to do with objects?  After all, we keep
  1839.       talking about    functions, not methods.     Well, since a method
  1840.       is just a function with an extra argument and    some fancier
  1841.       semantics about where    it's found, we can use autoloading for
  1842.  
  1843.  
  1844.  
  1845.      Page 28                        (printed 10/23/98)
  1846.  
  1847.  
  1848.  
  1849.  
  1850.  
  1851.  
  1852.      PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  1853.  
  1854.  
  1855.  
  1856.       methods, too.     Perl doesn't start looking for    an AUTOLOAD
  1857.       method until it has exhausted    the recursive hunt up through
  1858.       @ISA,    though.     Some programmers have even been known to
  1859.       define a UNIVERSAL::AUTOLOAD method to trap unresolved
  1860.       method calls to any kind of object.
  1861.  
  1862.       AAAAuuuuttttoooollllooooaaaaddddeeeedddd DDDDaaaattttaaaa MMMMeeeetttthhhhooooddddssss
  1863.  
  1864.       You probably began to    get a little suspicious    about the
  1865.       duplicated code way back earlier when    we first showed    you
  1866.       the Person class, and    then later the Employee    class.    Each
  1867.       method used to access    the hash fields    looked virtually
  1868.       identical.  This should have tickled that great programming
  1869.       virtue, Impatience, but for the time,    we let Laziness    win
  1870.       out, and so did nothing.  Proxy methods can cure this.
  1871.  
  1872.       Instead of writing a new function every time we want a new
  1873.       data field, we'll use    the autoload mechanism to generate
  1874.       (actually, mimic) methods on the fly.     To verify that    we're
  1875.       accessing a valid member, we will check against an
  1876.       _permitted (pronounced "under-permitted") field, which is a
  1877.       reference to a file-scoped lexical (like a C file static)
  1878.       hash of permitted fields in this record called %fields.  Why
  1879.       the underscore?  For the same    reason as the _CENSUS field we
  1880.       once used: as    a marker that means "for internal use only".
  1881.  
  1882.       Here's what the module initialization    code and class
  1883.       constructor will look    like when taking this approach:
  1884.  
  1885.           package Person;
  1886.           use Carp;
  1887.           use vars qw($AUTOLOAD);  # it's a    package    global
  1888.  
  1889.           my %fields = (
  1890.           name          => undef,
  1891.           age          => undef,
  1892.           peers          => undef,
  1893.           );
  1894.  
  1895.           sub new {
  1896.           my $that  = shift;
  1897.           my $class = ref($that) || $that;
  1898.           my $self  = {
  1899.               _permitted => \%fields,
  1900.               %fields,
  1901.           };
  1902.           bless    $self, $class;
  1903.           return $self;
  1904.           }
  1905.  
  1906.       If we    wanted our record to have default values, we could
  1907.       fill those in    where current we have undef in the %fields
  1908.  
  1909.  
  1910.  
  1911.      Page 29                        (printed 10/23/98)
  1912.  
  1913.  
  1914.  
  1915.  
  1916.  
  1917.  
  1918.      PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  1919.  
  1920.  
  1921.  
  1922.       hash.
  1923.  
  1924.       Notice how we    saved a    reference to our class data on the
  1925.       object itself?  Remember that    it's important to access class
  1926.       data through the object itself instead of having any method
  1927.       reference %fields directly, or else you won't    have a decent
  1928.       inheritance.
  1929.  
  1930.       The real magic, though, is going to reside in    our proxy
  1931.       method, which    will handle all    calls to undefined methods for
  1932.       objects of class Person (or subclasses of Person).  It has
  1933.       to be    called AUTOLOAD.  Again, it's all caps because it's
  1934.       called for us    implicitly by Perl itself, not by a user
  1935.       directly.
  1936.  
  1937.           sub AUTOLOAD {
  1938.           my $self = shift;
  1939.           my $type = ref($self)
  1940.                   or croak "$self is not an    object";
  1941.  
  1942.           my $name = $AUTOLOAD;
  1943.           $name    =~ s/.*://;   #    strip fully-qualified portion
  1944.  
  1945.           unless (exists $self->{_permitted}->{$name} )    {
  1946.               croak "Can't access `$name' field    in class $type";
  1947.           }
  1948.  
  1949.           if (@_) {
  1950.               return $self->{$name} = shift;
  1951.           } else {
  1952.               return $self->{$name};
  1953.           }
  1954.           }
  1955.  
  1956.       Pretty nifty,    eh?  All we have to do to add new data fields
  1957.       is modify %fields.  No new functions need be written.
  1958.  
  1959.       I could have avoided the _permitted field entirely, but I
  1960.       wanted to demonstrate    how to store a reference to class data
  1961.       on the object    so you wouldn't    have to    access that class data
  1962.       directly from    an object method.
  1963.  
  1964.       IIIInnnnhhhheeeerrrriiiitttteeeedddd AAAAuuuuttttoooollllooooaaaaddddeeeedddd DDDDaaaattttaaaa MMMMeeeetttthhhhooooddddssss
  1965.  
  1966.       But what about inheritance?  Can we define our Employee
  1967.       class    similarly?  Yes, so long as we're careful enough.
  1968.  
  1969.       Here's how to    be careful:
  1970.  
  1971.  
  1972.  
  1973.  
  1974.  
  1975.  
  1976.  
  1977.      Page 30                        (printed 10/23/98)
  1978.  
  1979.  
  1980.  
  1981.  
  1982.  
  1983.  
  1984.      PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  1985.  
  1986.  
  1987.  
  1988.           package Employee;
  1989.           use Person;
  1990.           use strict;
  1991.           use vars qw(@ISA);
  1992.           @ISA = qw(Person);
  1993.  
  1994.           my %fields = (
  1995.           id          => undef,
  1996.           salary      => undef,
  1997.           );
  1998.  
  1999.           sub new {
  2000.           my $that  = shift;
  2001.           my $class = ref($that) || $that;
  2002.           my $self = bless $that->SUPER::new(),    $class;
  2003.           my($element);
  2004.           foreach $element (keys %fields) {
  2005.               $self->{_permitted}->{$element} =    $fields{$element};
  2006.           }
  2007.           @{$self}{keys    %fields} = values %fields;
  2008.           return $self;
  2009.           }
  2010.  
  2011.       Once we've done this,    we don't even need to have an AUTOLOAD
  2012.       function in the Employee package, because we'll grab
  2013.       Person's version of that via inheritance, and    it will    all
  2014.       work out just    fine.
  2015.  
  2016.      MMMMeeeettttaaaaccccllllaaaassssssssiiiiccccaaaallll TTTToooooooollllssss
  2017.       Even though proxy methods can    provide    a more convenient
  2018.       approach to making more struct-like classes than tediously
  2019.       coding up data methods as functions, it still    leaves a bit
  2020.       to be    desired.  For one thing, it means you have to handle
  2021.       bogus    calls that you don't mean to trap via your proxy.  It
  2022.       also means you have to be quite careful when dealing with
  2023.       inheritance, as detailed above.
  2024.  
  2025.       Perl programmers have    responded to this by creating several
  2026.       different class construction classes.     These metaclasses are
  2027.       classes that create other classes.  A    couple worth looking
  2028.       at are Class::Struct and Alias.  These and other related
  2029.       metaclasses can be found in the modules directory on CPAN.
  2030.  
  2031.       CCCCllllaaaassssssss::::::::SSSSttttrrrruuuucccctttt
  2032.  
  2033.       One of the older ones    is Class::Struct.  In fact, its    syntax
  2034.       and interface    were sketched out long before perl5 even
  2035.       solidified into a real thing.     What it does is provide you a
  2036.       way to "declare" a class as having objects whose fields are
  2037.       of a specific    type.  The function that does this is called,
  2038.       not surprisingly enough, _s_t_r_u_c_t().  Because structures or
  2039.       records are not base types in    Perl, each time    you want to
  2040.  
  2041.  
  2042.  
  2043.      Page 31                        (printed 10/23/98)
  2044.  
  2045.  
  2046.  
  2047.  
  2048.  
  2049.  
  2050.      PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  2051.  
  2052.  
  2053.  
  2054.       create a class to provide a record-like data object, you
  2055.       yourself have    to define a _n_e_w() method, plus separate    data-
  2056.       access methods for each of that record's fields.  You'll
  2057.       quickly become bored with this process.  The
  2058.       _C_l_a_s_s::_S_t_r_u_c_t::_s_t_r_u_c_t() function alleviates this tedium.
  2059.  
  2060.       Here's a simple example of using it:
  2061.  
  2062.           use Class::Struct    qw(struct);
  2063.           use Jobbie;  # user-defined; see below
  2064.  
  2065.           struct 'Fred' => {
  2066.           one         =>    '$',
  2067.           many         =>    '@',
  2068.           profession =>    Jobbie,     # calls Jobbie->new()
  2069.           };
  2070.  
  2071.           $ob = Fred->new;
  2072.           $ob->one("hmmmm");
  2073.  
  2074.           $ob->many(0, "here");
  2075.           $ob->many(1, "you");
  2076.           $ob->many(2, "go");
  2077.           print "Just set: ", $ob->many(2),    "\n";
  2078.  
  2079.           $ob->profession->salary(10_000);
  2080.  
  2081.       You can declare types    in the struct to be basic Perl types,
  2082.       or user-defined types    (classes).  User types will be
  2083.       initialized by calling that class's _n_e_w() method.
  2084.  
  2085.       Here's a real-world example of using struct generation.
  2086.       Let's    say you    wanted to override Perl's idea of
  2087.       _g_e_t_h_o_s_t_b_y_n_a_m_e() and _g_e_t_h_o_s_t_b_y_a_d_d_r() so that they would
  2088.       return objects that acted like C structures.    We don't care
  2089.       about    high-falutin' OO gunk.    All we want is for these
  2090.       objects to act like structs in the C sense.
  2091.  
  2092.           use Socket;
  2093.           use Net::hostent;
  2094.           $h = gethostbyname("perl.com");  # object    return
  2095.           printf "perl.com's real name is %s, address %s\n",
  2096.           $h->name, inet_ntoa($h->addr);
  2097.  
  2098.       Here's how to    do this    using the Class::Struct    module.     The
  2099.       crux is going    to be this call:
  2100.  
  2101.  
  2102.  
  2103.  
  2104.  
  2105.  
  2106.  
  2107.  
  2108.  
  2109.      Page 32                        (printed 10/23/98)
  2110.  
  2111.  
  2112.  
  2113.  
  2114.  
  2115.  
  2116.      PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  2117.  
  2118.  
  2119.  
  2120.           struct 'Net::hostent' => [      # note bracket
  2121.           name         =>    '$',
  2122.           aliases    =>    '@',
  2123.           addrtype   =>    '$',
  2124.           'length'   =>    '$',
  2125.           addr_list  =>    '@',
  2126.            ];
  2127.  
  2128.       Which    creates    object methods of those    names and types.  It
  2129.       even creates a _n_e_w() method for us.
  2130.  
  2131.       We could also    have implemented our object this way:
  2132.  
  2133.           struct 'Net::hostent' => {      # note brace
  2134.           name         =>    '$',
  2135.           aliases    =>    '@',
  2136.           addrtype   =>    '$',
  2137.           'length'   =>    '$',
  2138.           addr_list  =>    '@',
  2139.            };
  2140.  
  2141.       and then Class::Struct would have used an anonymous hash as
  2142.       the object type, instead of an anonymous array.  The array
  2143.       is faster and    smaller, but the hash works out    better if you
  2144.       eventually want to do    inheritance.  Since for    this struct-
  2145.       like object we aren't    planning on inheritance, this time
  2146.       we'll    opt for    better speed and size over better flexibility.
  2147.  
  2148.       Here's the whole implementation:
  2149.  
  2150.           package Net::hostent;
  2151.           use strict;
  2152.  
  2153.           BEGIN {
  2154.           use Exporter     ();
  2155.           use vars     qw(@EXPORT @EXPORT_OK %EXPORT_TAGS);
  2156.           @EXPORT      = qw(gethostbyname gethostbyaddr    gethost);
  2157.           @EXPORT_OK   = qw(
  2158.                      $h_name         @h_aliases
  2159.                      $h_addrtype     $h_length
  2160.                      @h_addr_list    $h_addr
  2161.                  );
  2162.           %EXPORT_TAGS = ( FIELDS => [ @EXPORT_OK, @EXPORT ] );
  2163.           }
  2164.           use vars        @EXPORT_OK;
  2165.  
  2166.           #    Class::Struct forbids use of @ISA
  2167.           sub import { goto    &Exporter::import }
  2168.  
  2169.  
  2170.  
  2171.  
  2172.  
  2173.  
  2174.  
  2175.      Page 33                        (printed 10/23/98)
  2176.  
  2177.  
  2178.  
  2179.  
  2180.  
  2181.  
  2182.      PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  2183.  
  2184.  
  2185.  
  2186.           use Class::Struct    qw(struct);
  2187.           struct 'Net::hostent' => [
  2188.          name         =>    '$',
  2189.          aliases     =>    '@',
  2190.          addrtype    =>    '$',
  2191.          'length'    =>    '$',
  2192.          addr_list   =>    '@',
  2193.           ];
  2194.  
  2195.           sub addr { shift->addr_list->[0] }
  2196.  
  2197.           sub populate (@) {
  2198.           return unless    @_;
  2199.           my $hob = new();  # Class::Struct made this!
  2200.           $h_name     =       $hob->[0]          = $_[0];
  2201.           @h_aliases  =    @{ $hob->[1] } = split ' ', $_[1];
  2202.           $h_addrtype =       $hob->[2]          = $_[2];
  2203.           $h_length   =       $hob->[3]          = $_[3];
  2204.           $h_addr     =                    $_[4];
  2205.           @h_addr_list = @{ $hob->[4] }    =      @_[ (4 .. $#_) ];
  2206.           return $hob;
  2207.           }
  2208.  
  2209.           sub gethostbyname    ($)  { populate(CORE::gethostbyname(shift)) }
  2210.  
  2211.           sub gethostbyaddr    ($;$) {
  2212.           my ($addr, $addrtype);
  2213.           $addr    = shift;
  2214.           require Socket unless    @_;
  2215.           $addrtype = @_ ? shift : Socket::AF_INET();
  2216.           populate(CORE::gethostbyaddr($addr, $addrtype))
  2217.           }
  2218.  
  2219.           sub gethost($) {
  2220.           if ($_[0] =~ /^\d+(?:\.\d+(?:\.\d+(?:\.\d+)?)?)?$/) {
  2221.              require Socket;
  2222.              &gethostbyaddr(Socket::inet_aton(shift));
  2223.           } else {
  2224.              &gethostbyname;
  2225.           }
  2226.           }
  2227.  
  2228.           1;
  2229.  
  2230.       We've    snuck in quite a fair bit of other concepts besides
  2231.       just dynamic class creation, like overriding core functions,
  2232.       import/export    bits, function prototyping, short-cut function
  2233.       call via &whatever, and function replacement with goto
  2234.       &whatever.  These all    mostly make sense from the perspective
  2235.       of a traditional module, but as you can see, we can also use
  2236.       them in an object module.
  2237.  
  2238.  
  2239.  
  2240.  
  2241.      Page 34                        (printed 10/23/98)
  2242.  
  2243.  
  2244.  
  2245.  
  2246.  
  2247.  
  2248.      PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  2249.  
  2250.  
  2251.  
  2252.       You can look at other    object-based, struct-like overrides of
  2253.       core functions in the    5.004 release of Perl in File::stat,
  2254.       Net::hostent,    Net::netent, Net::protoent, Net::servent,
  2255.       Time::gmtime,    Time::localtime, User::grent, and User::pwent.
  2256.       These    modules    have a final component that's all lowercase,
  2257.       by convention    reserved for compiler pragmas, because they
  2258.       affect the compilation and change a builtin function.     They
  2259.       also have the    type names that    a C programmer would most
  2260.       expect.
  2261.  
  2262.       DDDDaaaattttaaaa MMMMeeeemmmmbbbbeeeerrrrssss aaaassss VVVVaaaarrrriiiiaaaabbbblllleeeessss
  2263.  
  2264.       If you're used to C++    objects, then you're accustomed    to
  2265.       being    able to    get at an object's data    members    as simple
  2266.       variables from within    a method.  The Alias module provides
  2267.       for this, as well as a good bit more,    such as    the
  2268.       possibility of private methods that the object can call but
  2269.       folks    outside    the class cannot.
  2270.  
  2271.       Here's an example of creating    a Person using the Alias
  2272.       module.  When    you update these magical instance variables,
  2273.       you automatically update value fields    in the hash.
  2274.       Convenient, eh?
  2275.  
  2276.           package Person;
  2277.  
  2278.           #    this is    the same as before...
  2279.           sub new {
  2280.            my $that  = shift;
  2281.            my $class = ref($that) || $that;
  2282.            my $self = {
  2283.               NAME  => undef,
  2284.               AGE   => undef,
  2285.               PEERS => [],
  2286.           };
  2287.           bless($self, $class);
  2288.           return $self;
  2289.           }
  2290.  
  2291.           use Alias    qw(attr);
  2292.           use vars qw($NAME    $AGE $PEERS);
  2293.  
  2294.           sub name {
  2295.           my $self = attr shift;
  2296.           if (@_) { $NAME = shift; }
  2297.           return    $NAME;
  2298.           }
  2299.  
  2300.  
  2301.  
  2302.  
  2303.  
  2304.  
  2305.  
  2306.  
  2307.      Page 35                        (printed 10/23/98)
  2308.  
  2309.  
  2310.  
  2311.  
  2312.  
  2313.  
  2314.      PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  2315.  
  2316.  
  2317.  
  2318.           sub age {
  2319.           my $self = attr shift;
  2320.           if (@_) { $AGE = shift; }
  2321.           return    $AGE;
  2322.           }
  2323.  
  2324.           sub peers    {
  2325.           my $self = attr shift;
  2326.           if (@_) { @PEERS = @_; }
  2327.           return    @PEERS;
  2328.           }
  2329.  
  2330.           sub exclaim {
  2331.           my $self = attr shift;
  2332.           return sprintf "Hi, I'm %s, age %d, working with %s",
  2333.               $NAME, $AGE, join(", ", @PEERS);
  2334.           }
  2335.  
  2336.           sub happy_birthday {
  2337.           my $self = attr shift;
  2338.           return ++$AGE;
  2339.           }
  2340.  
  2341.       The need for the use vars declaration    is because what    Alias
  2342.       does is play with package globals with the same name as the
  2343.       fields.  To use globals while    use strict is in effect, you
  2344.       have to predeclare them.  These package variables are
  2345.       localized to the block enclosing the _a_t_t_r() call just    as if
  2346.       you'd    used a _l_o_c_a_l() on them.     However, that means that
  2347.       they're still    considered global variables with temporary
  2348.       values, just as with any other _l_o_c_a_l().
  2349.  
  2350.       It would be nice to combine Alias with something like
  2351.       Class::Struct    or Class::MethodMaker.
  2352.  
  2353.       NNNNOOOOTTTTEEEESSSS
  2354.  
  2355.       OOOObbbbjjjjeeeecccctttt TTTTeeeerrrrmmmmiiiinnnnoooollllooooggggyyyy
  2356.  
  2357.       In the various OO literature,    it seems that a    lot of
  2358.       different words are used to describe only a few different
  2359.       concepts.  If    you're not already an object programmer, then
  2360.       you don't need to worry about    all these fancy    words.    But if
  2361.       you are, then    you might like to know how to get at the same
  2362.       concepts in Perl.
  2363.  
  2364.       For example, it's common to call an object an    _i_n_s_t_a_n_c_e of a
  2365.       class    and to call those objects' methods _i_n_s_t_a_n_c_e _m_e_t_h_o_d_s.
  2366.       Data fields peculiar to each object are often    called
  2367.       _i_n_s_t_a_n_c_e _d_a_t_a    or _o_b_j_e_c_t _a_t_t_r_i_b_u_t_e_s, and data fields common
  2368.       to all members of that class are _c_l_a_s_s _d_a_t_a, _c_l_a_s_s
  2369.       _a_t_t_r_i_b_u_t_e_s, or _s_t_a_t_i_c    _d_a_t_a _m_e_m_b_e_r_s.
  2370.  
  2371.  
  2372.  
  2373.      Page 36                        (printed 10/23/98)
  2374.  
  2375.  
  2376.  
  2377.  
  2378.  
  2379.  
  2380.      PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  2381.  
  2382.  
  2383.  
  2384.       Also,    _b_a_s_e _c_l_a_s_s, _g_e_n_e_r_i_c _c_l_a_s_s, and _s_u_p_e_r_c_l_a_s_s all describe
  2385.       the same notion, whereas _d_e_r_i_v_e_d _c_l_a_s_s, _s_p_e_c_i_f_i_c _c_l_a_s_s, and
  2386.       _s_u_b_c_l_a_s_s describe the    other related one.
  2387.  
  2388.       C++ programmers have _s_t_a_t_i_c _m_e_t_h_o_d_s and _v_i_r_t_u_a_l _m_e_t_h_o_d_s, but
  2389.       Perl only has    _c_l_a_s_s _m_e_t_h_o_d_s and _o_b_j_e_c_t _m_e_t_h_o_d_s.  Actually,
  2390.       Perl only has    methods.  Whether a method gets    used as    a
  2391.       class    or object method is by usage only.  You    could
  2392.       accidentally call a class method (one    expecting a string
  2393.       argument) on an object (one expecting    a reference), or vice
  2394.       versa.
  2395.  
  2396.       From the C++ perspective, all    methods    in Perl    are virtual.
  2397.       This,    by the way, is why they    are never checked for function
  2398.       prototypes in    the argument list as regular builtin and
  2399.       user-defined functions can be.
  2400.  
  2401.       Because a class is itself something of an object, Perl's
  2402.       classes can be taken as describing both a "class as meta-
  2403.       object" (also    called _o_b_j_e_c_t _f_a_c_t_o_r_y) philosophy and the
  2404.       "class as type definition" (_d_e_c_l_a_r_i_n_g    behaviour, not
  2405.       _d_e_f_i_n_i_n_g mechanism) idea.  C++ supports the latter notion,
  2406.       but not the former.
  2407.  
  2408.      SSSSEEEEEEEE AAAALLLLSSSSOOOO
  2409.       The following    manpages will doubtless    provide    more
  2410.       background for this one:  the    _p_e_r_l_m_o_d    manpage, the _p_e_r_l_r_e_f
  2411.       manpage, the _p_e_r_l_o_b_j manpage,    the _p_e_r_l_b_o_t manpage, the
  2412.       _p_e_r_l_t_i_e manpage, and the _o_v_e_r_l_o_a_d manpage.
  2413.  
  2414.      AAAAUUUUTTTTHHHHOOOORRRR AAAANNNNDDDD    CCCCOOOOPPPPYYYYRRRRIIIIGGGGHHHHTTTT
  2415.       Copyright (c)    1997, 1998 Tom Christiansen All    rights
  2416.       reserved.
  2417.  
  2418.       When included    as part    of the Standard    Version    of Perl, or as
  2419.       part of its complete documentation whether printed or
  2420.       otherwise, this work may be distributed only under the terms
  2421.       of Perl's Artistic License.  Any distribution    of this    file
  2422.       or derivatives thereof _o_u_t_s_i_d_e of that package require that
  2423.       special arrangements be made with copyright holder.
  2424.  
  2425.       Irrespective of its distribution, all    code examples in this
  2426.       file are hereby placed into the public domain.  You are
  2427.       permitted and    encouraged to use this code in your own
  2428.       programs for fun or for profit as you    see fit.  A simple
  2429.       comment in the code giving credit would be courteous but is
  2430.       not required.
  2431.  
  2432.      CCCCOOOOPPPPYYYYRRRRIIIIGGGGHHHHTTTT
  2433.  
  2434.  
  2435.  
  2436.  
  2437.  
  2438.  
  2439.      Page 37                        (printed 10/23/98)
  2440.  
  2441.  
  2442.  
  2443.  
  2444.  
  2445.  
  2446.      PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))     22223333////JJJJuuuullll////99998888 ((((ppppeeeerrrrllll 5555....000000005555,,,, ppppaaaattttcccchhhh 00002222))))       PPPPEEEERRRRLLLLTTTTOOOOOOOOTTTT((((1111))))
  2447.  
  2448.  
  2449.  
  2450.       AAAAcccckkkknnnnoooowwwwlllleeeeddddggggmmmmeeeennnnttttssss
  2451.  
  2452.       Thanks to Larry Wall,    Roderick Schertler, Gurusamy Sarathy,
  2453.       Dean Roehrich, Raphael Manfredi, Brent Halsey, Greg Bacon,
  2454.       Brad Appleton, and many others for their helpful comments.
  2455.  
  2456.  
  2457.  
  2458.  
  2459.  
  2460.  
  2461.  
  2462.  
  2463.  
  2464.  
  2465.  
  2466.  
  2467.  
  2468.  
  2469.  
  2470.  
  2471.  
  2472.  
  2473.  
  2474.  
  2475.  
  2476.  
  2477.  
  2478.  
  2479.  
  2480.  
  2481.  
  2482.  
  2483.  
  2484.  
  2485.  
  2486.  
  2487.  
  2488.  
  2489.  
  2490.  
  2491.  
  2492.  
  2493.  
  2494.  
  2495.  
  2496.  
  2497.  
  2498.  
  2499.  
  2500.  
  2501.  
  2502.  
  2503.  
  2504.  
  2505.      Page 38                        (printed 10/23/98)
  2506.  
  2507.  
  2508.  
  2509.